import config from "@/common/config.js"
class Http {
	constructor() {}
	request({
		url,
		data = {},
		method = "GET",
		header = {},
		loading
	}) {
		return new Promise((resolve, reject) => {
			this._request(url, resolve, reject, data, header, loading)
		})
	}

	async _request(url, resolve, reject, data, method, header, loading) {
		if (loading) {
			uni.showLoading({
				title: '请稍后',
				mask: true
			})
		}
		let fullURL = config.baseURL + url;
		let userInfo = uni.getStorageSync('userInfo');
		let date_pre = new Date('1970/01/01 00:00:00:00'),
			date_cur = new Date(),
			timestamp = date_cur.getTime() - date_pre.getTime();
		let [error, response] = await uni.request({
			url: fullURL,
			data: {
				'sid': userInfo.sid,
				'data': JSON.stringify(data),
				'timestamp': timestamp,
				'sign_type': 'md5',
				'sign': userInfo.token
			},
			method: method,
			header: Object.assign(config.header, header)
		});
		if (!loading) {
			uni.hideLoading();
		}
		if (response.data) {
			if (response.data.error == '请先登录' || response.data.code == 10005) {
				//10005为无效Sid
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				});
				uni.removeStorage({
					key: 'secret_key'
				});
				uni.navigateTo({
					url: '/pages/public/login'
				});
			} else if (response.data.code == 10006) {
				//无效秘钥
				uni.request({
					url: `${config.baseURL}user/get_lock`,
					method: "POST",
					data: {
						"sid": "",
						"timestamp": timestamp,
						"sign_type": "md5",
						"sign": ""
					},
					success: (res) => {
						if (res.data.code == "0") {
							let secret_key = res.data.data.secret_key;
							uni.setStorageSync('secret_key', secret_key);
						}
					}
				})
			} else if (response.data.code == 0 && (url == 'user/login' || url == 'user/captcha_verify')) {
				resolve(response.data)
			} else if (response.data.code == 0) {
				resolve(response.data.data)
			} else {
				uni.showToast({
					title: response.data.error,
				})
			}
		} else {
			console.info('请求失败：', error);
			reject(error)
		}
	}
}
export { Http }
